﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using EvinceUI.Models;
using EvincePayroll.Data;
using System.IO;
using System.Configuration;
using EvinceUI.JQueryDataTable.Model;
using EvincePayroll.Utility;
using System.Text;
using SignalR;
using EvinceUI.Helper;

namespace EvinceUI.Controllers
{
    
    public class AccountController : Controller
    {
       public static EmployeeData empData = null;
        //
        // GET: /Account/Login
        string userEmailId = ConfigurationManager.AppSettings["LoginID"].ToString();
        public ActionResult Login()
        {
            return View();
        }


        //public void sendingemail()
        //{
        //    MailSending sent = new MailSending();
        //    sent.SendMail("sandeep.modi123@gmail.com", "No Sub", "Hi sandeep");
        //}


        //
        // POST: /Account/Login


        public string GetUserName()
        {
            string result = string.Empty;
            if (empData!= null)
            {
                result = empData.ID.ToString();

              //  result=employeeData.ID.ToString();
            }
            return result;
        }


        [HttpPost]
        public ActionResult Login(LogOnModel model, string returnUrl)
        {
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            EvincePayrollService pageTemplateService = new EvincePayrollService(ServiceTypes.PageTemplate);
           
            if (ModelState.IsValid )
            {
                if (accountService.AuthenticateLogin(model.UserName, model.Password))
                {
                   
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    Session["EmployeeData"] = employeeService.GetUser(model.UserName);
                    empData = Session["EmployeeData"] as EmployeeData;
                    GlobalHost.DependencyResolver.Register(typeof(IConnectionIdGenerator), () => new UserIdClientIdFactory());
                    var checkIn = Session["EmployeeData"] as EmployeeData;
                    Session["CheckIn"] = checkIn.CheckInStatus;
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        var isAdmin = Session["EmployeeData"] as EmployeeData;
                        if(isAdmin.UserRoleId.ToString()!=Constants.ADMIN_ROLE_ID)
                            Session["Templates"] = pageTemplateService.GetPageTemplateList();


                        return RedirectToAction("DashBoard", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [Authorize]
        public ActionResult GetUserProfile(string email, string flag)
        {
            EmployeeData emp = new EmployeeData();
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
            if (flag == string.Empty || flag == null)
            {


                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                if (employee != null)
                {
                    emp = employeeService.GetUser(employee.Email);
                    //ChatHub chat = new ChatHub();
                    //chat.GoOnline(emp);
                }
                else
                {
                    return RedirectToAction("Login", "Login");
                }
            }
            else if (flag == "1")
            {
                emp = employeeService.GetUser(email);
                ViewBag.Flag = flag;
            }
            return View(emp);

        }
        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            try
            {
                FormsAuthentication.SignOut();
                EmployeeData employeeData = (EmployeeData)Session["EmployeeData"];
                if (employeeData != null)
                {
                    EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
                    bool employeeLogout = accountService.Logout(employeeData.Email);
                }
                Session["EmployeeData"]=null;
                Session["CheckIn"]=null;

            }
            catch (Exception ex)
            {

                LogEngine.Log(ex.Message);
                Response.Write(ex);
                throw;
            }
            return RedirectToAction("Login", "Account");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            string[] gender = new string[] { "Male", "Female" };
            ViewBag.Gender = gender;
            return View();
        }

        //
        // POST: /Account/Register

        public void MarkAubsent()
        {
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            accountService.MarkAubsent();
           // return View();
        }

        [HttpPost]
        public ActionResult Register(EmployeeData model,HttpPostedFileBase profileImage, string date, string month, string year)
        {
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            List<EmployeeData> list = null;
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                //MembershipCreateStatus createStatus;
                //Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                bool result = accountService.CheckExistingUser(model.Email);
                if (result == true)
                {
                    if (profileImage != null && profileImage.ContentLength > 0)
                    {
                        // extract only the fielname
                        var fileName = Path.GetFileName(profileImage.FileName);
                        // store the file inside ~/App_Data/uploads folder
                        var path = Path.Combine(Server.MapPath("~/Images/Employee"), fileName);
                        profileImage.SaveAs(path);
                        model.Image1 = profileImage.FileName;
                        
                        
                    }
                    model.DateOfBirth = date + "/" + month + "/" + year;
                    model.IsActive = 0;
                    model.IsOnline = false;
                   list = accountService.RegisterEmployee(model, userEmailId);
                    ViewBag.Success = "Success";
                    ViewBag.Message = "Registered Successfully.";
                }
                else
                {
                    ViewBag.Message = "User with this email ID is already exist.";
                }
                string[] gender = new string[] { "Male", "Female" };
                ViewBag.Gender = gender;
                if (list != null)
                {
                    FormsAuthentication.SetAuthCookie(model.Email, false /* createPersistentCookie */);
                    //return RedirectToAction("Index", "Home");
                }
                
            }

            // If we got this far, something failed, redisplay form
            return View();
        }

        

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
           

                bool emp1 = false;
                EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
                EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EmployeeData emp = employeeService.GetUser(employee.Email);
                EmployeeData empdata = new EmployeeData();
                var temp = emp.Password;
                if (temp == Cryptography.EncryptStringAES(model.OldPassword, "evincePassword") && model.NewPassword == model.ConfirmPassword)
                {
                    empdata.Password = model.NewPassword;
                    emp1 = accountService.GetUpdatePassword(empdata, employee.Email);


                }
                if (emp1 == true)
                {
                    ViewBag.Message = "Success";
                }
                else
                {
                    ViewBag.Message = "Failed";
                }

              
           

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess
        [Authorize]
        public ActionResult GetUpdatedUserProfile()
        {
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EmployeeData emp = employeeService.GetUser(employee.Email);
            string[] gender = new string[] { "Male", "Female" };
            ViewBag.Gender = gender;
            return View(emp);

        }
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetUpdatedUserProfile(EmployeeData emdata, HttpPostedFileBase profileImage)
        {
            if (profileImage != null && profileImage.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(profileImage.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/img/Employee"), fileName);
                profileImage.SaveAs(path);
                emdata.Image1 = profileImage.FileName;


            }
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            bool emp = employeeService.GetUpdatedUserProfile(emdata, employee.Email);
            return RedirectToAction("GetUserProfile");



        }

        //
        // GET: /Account/ChangePassword


        
        [Authorize]
        public ActionResult ChangePassword()
        {

            return View();

        }
        //
        // POST: /Account/ChangePassword
        //[Authorize]
        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult ChangePassword(string oldPass, string newpass, string confirmpass)
        //{
        //    bool emp1 = false;
        //    ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
        //    EmployeeData employee = (EmployeeData)Session["EmployeeData"];
        //    EmployeeData emp = client.GetEmployeeData(employee.Email);
        //    EmployeeData empdata = new EmployeeData();
        //    var temp = emp.Password;
        //    if (temp == Cryptography.EncryptStringAES(oldPass, "evincePassword") && newpass == confirmpass)
        //    {
        //        empdata.Password = newpass;
        //        emp1 = client.GetUpdatePassword(empdata, employee.Email);


        //    }
        //    if (emp1 == true)
        //    {
        //        ViewBag.Message = "Success";
        //    }
        //    else
        //    {
        //        ViewBag.Message = "Failed";
        //    }

        //    return View();


        //}
        [Authorize]
        public ActionResult ChangePasswordSuccess()
        {

            return View();

        }
        [Authorize]
        public PartialViewResult _AddExperince()
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService homeService = new EvincePayrollService(ServiceTypes.Home);
            ViewBag.EmploymentType = homeService.GetAppOption(employee.Email, Constants.EMPLOYEMENT_TYPE);
            return PartialView();
        }
        [Authorize]
        public ActionResult AjaxGetAddExperince(JQueryDataTableParamModel param)
        {

            List<ExperienceData> experinceList;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
            experinceList = employeeService.GetExperinceByUserId(employee.Email, employee.ID.ToString());
            if (experinceList != null)
            {
                IEnumerable<ExperienceData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered

                    var employeeIdFilter = Convert.ToString(Request["sSearch_1"]);
                    var EmployerNameFilter = Convert.ToString(Request["sSearch_2"]);





                    //Optionally check whether the columns are searchable at all

                    var isEmployeeIdSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                    var isEmployerNameSearchable = Convert.ToBoolean(Request["bSearchable_2"]);





                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();
                        filter.Append("(").Append(expression.Replace("[FIELD]", "EmployeeId.ToUpper()")).Append(") ||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "EmployerName.ToString().ToUpper()")).Append(")||");
                        filteredRequests = experinceList;
                    }
                    else
                    {

                        filteredRequests = experinceList
                        .Where(d => isEmployeeIdSearchable && d.EmployeeId.ToString().Contains(param.sSearch.Trim().ToLower())
                        ||
                        isEmployerNameSearchable && d.EmployerName.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())

                        );

                    }
                }
                else
                {
                    filteredRequests = experinceList;

                }

                var isEmployeeId = Convert.ToBoolean(Request["bSortable_1"]);
                var isEmployerName = Convert.ToBoolean(Request["bSortable_2"]);




                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<ExperienceData, string> orderingFunction = (d => sortColumnIndex == 1 && isEmployeeId ? d.EmployeeId.ToString() :
                sortColumnIndex == 2 && isEmployerName ? d.EmployerName.ToString() :

                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] {
                                 p.ExperienceId.ToString(),
                            p.EmployeeId.ToString(),
                            p.EmployerName,
                            p.ContactNumber,
                            p.Address,
                            p.EmploymentTypeString,
                            p.EmploymentFrom,
                            p.EmploymentTo,
                            p.Designation,
                            p.AnnualSalary,
                            GetEditEmploymentRecord(p.ExperienceId.ToString())
                             
                         };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = experinceList.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);

        }
        [Authorize]
        public string GetEditEmploymentRecord(string employmentId)
        {
            string url = string.Empty;
            url = string.Format("<a href=\"#\" onclick=\"EditExperience('{0}')\">Edit</a>&nbsp;<a href=\"#\" onclick=\"DeleteExperience('{1}')\">Delete</a>", employmentId, employmentId);
            return url;
        }
        [Authorize]
        public ActionResult EditExperience(string experienceId)
        {


            ExperienceData result = null;
            if (experienceId != "")
            {
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
                result = employeeService.EditExperience(experienceId, employee.Email);
            }
            return Json(new { result }, JsonRequestBehavior.AllowGet);

        }
        [Authorize]
        public ActionResult DeleteExperience(string experienceId)
        {


            bool result = false;
            if (experienceId != "")
            {
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);
                result = employeeService.DeleteExperience(experienceId, employee.Email);
            }
            return Json(new { Result = result }, JsonRequestBehavior.AllowGet);

        }

        [Authorize]
        private string GetExpression(string p)
        {
            throw new NotImplementedException();
        }






        [Authorize]
        public ActionResult AddYourExperince(ExperienceData experience, string flag, string experinceId)
        {
            if (flag == null)
                flag = Constants.NA;
            if (experinceId == null)
                experinceId = Constants.NA;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService employeeService = new EvincePayrollService(ServiceTypes.Employee);

            bool result = employeeService.AddYourExperince(experience, employee.Email, flag, experinceId);

            return Json(new { Result = "Success" }, JsonRequestBehavior.AllowGet);
        }

        [Authorize]
        public ActionResult GetOnlineUsers()
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            List<EmployeeData> onlineUsersList=null;
            if (employee != null)
            {
                EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
                onlineUsersList = accountService.GetOnlineUsers(employee.Email);
            }
            return Json(new { Result = onlineUsersList }, JsonRequestBehavior.AllowGet);
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
